/**
 * 用户删除接口测试用例
 *
 * Created by snowingsea on 2020/02/01.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');

module.exports = describe('/DELETE users/:id.json', function () {
  function url(userId) {
    return `/users/${userId}.json`;
  }
  const administrator = new Administrator();
  const newUserIds = [];
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'delete');
  common.should.be.administrator(uri, url, 'delete');

  // 正常删除
  it('it should DELETE a user', function (done) {
    let newUser;
    administrator.createRandomTester()
      .then((tester) => {
        newUser = tester;
        return administrator.login();
      })
      .then(() => {
        chai.request(uri)
          .delete(url(newUser.userId))
          .set('Authorization', `Bearer ${administrator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(204);
            // 查询
            chai.request(uri)
              .get(url(newUser.userId))
              .set('Authorization', `Bearer ${administrator.token.accessToken}`)
              .end((err, res) => {
                res.should.have.status(404);
                common.should.be.errorMessage(res.body);
                done();
              });
          });
      })
      .catch(done);
  });

  // 删除不存在的用户
  it('it should fail to delete a user when the user is not exists', function (done) {
    let userId;
    administrator.createRandomTester()
      .then((tester) => {
        userId = tester.userId;
        return administrator.removeUser(userId);
      })
      .then(() => administrator.login())
      .then(() => {
        chai.request(uri)
          .delete(url(userId))
          .set('Authorization', `Bearer ${administrator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可删除超级用户
  it('it should fail to delete a superuser', function (done) {
    administrator.login()
      .then(() => {
        chai.request(uri)
          .delete(url(administrator.userId))
          .set('Authorization', `Bearer ${administrator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(416);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
